//
//  ViewController.m
//  ModelContrast
//
//  Created by Cluy on 15/6/17.
//  Copyright (c) 2015年 sunflowers. All rights reserved.
//

#import "CompareViewController.h"
#import "DBManager.h"
#import "Constant.h"
@interface CompareViewController ()

@end

@implementation CompareViewController
- (void)viewDidLoad{
    //默认高亮
    _hightLineBtn.backgroundColor = [UIColor blueColor];
    
    tableVC =[[YDTableView alloc] init];
    tableVC.getValuedelegate = self;
    [self initGesture];
    
    _titleTableView.hidden = YES;
    _titleTableView.getValuedelegate = self;
    _titleTableView.changeCellDelegate = self;
    _titleTableView.allowsSelection = NO;
    _titleTableView.isDifferent = NO;
    
    _item2TableView.hidden = YES;
    _item2TableView.getValuedelegate = self;
    _item2TableView.allowsSelection = NO;
    _item2TableView.isDifferent = NO;
    
    _titleTableView.scrollEnabled = YES;
    _scrollerView.showsVerticalScrollIndicator = NO;
    _scrollerView.showsHorizontalScrollIndicator = NO;
    _scrollerView.clipsToBounds = YES;
    _scrollerView.delegate = self;
    self.addBtn.tag = 1003;
    
    dbManager = [[DBManager alloc]initWithDBName:COMPARE_DB_NAME];
    if(![dbManager readyDatabse]){
        [dbManager openDB];
    }
    [self loadData];//更新数据
    [self loadCarBrandList]; //获取车系数据

}
#pragma  mark ----------------------------------------
#pragma  mark 手势
- (void)initGesture{
    // 单击的 Recognizer
    UITapGestureRecognizer* singleRecognizer;
    singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(SingleTap:  )]; //点击的次数
    singleRecognizer.delegate =self;
    singleRecognizer.numberOfTapsRequired = 1; // 单击
    //给self.view添加一个手势监测；
    [self.view addGestureRecognizer:singleRecognizer];
}
-(void)SingleTap:(UITapGestureRecognizer*)recognizer{
    NSLog(@"touch point = %@ \n tableVc.origin = %@",NSStringFromCGPoint([recognizer locationInView:self.view]),NSStringFromCGPoint(tableVC.frame.origin));
    if(tableVC.hidden == NO){
        tableVC.hidden = YES;
    }
    
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    CGPoint recognizerPoint = [touch locationInView:self.view];
    if (!CGRectContainsPoint([tableVC.superview convertRect:tableVC.frame toView:self.view], recognizerPoint)) {
            return YES;

    }else{
        return NO;
    }

}
#pragma mark 创建表
-(void)loadData
{
    
        // 创建 对于车型数据
//        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//        NSString *documentsDirectory = [paths objectAtIndex:0];
//        NSString *filepath =[documentsDirectory stringByAppendingPathComponent:@"CompeteInfo.json"];
//        NSString *jsonStr=[NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil];
//        idx = 0;
//        [jsonStr enumerateLinesUsingBlock:^(NSString* line, BOOL* shouldStop) {
//            idx++;
//            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:[line dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:NULL];
//            if (![dbManager isTableOK:TABLE_COMPLETEINFO]) {
//                NSArray *fields = [jsonDic allKeys]; //字段名称
//                if (![dbManager createTable:TABLE_COMPLETEINFO fields:fields]) {
//                    NSLog(@"创建表失败");
//                }
//            }
//            NSArray *fieldsValue = [jsonDic allValues]; //字段对应的值
//            [dbManager insertTable:TABLE_COMPLETEINFO withArr:fieldsValue];
//    
//        }];
//    
//    
//        //创建 carinfo table
//        NSArray *arry = @[@"brandId",@"bName",@"modelId",@"mName"];
//        NSArray *carList =[dbManager selectFromTable:TABLE_COMPLETEINFO fields:arry whereParam:nil groupBy:@[@"brandId"] orderby:nil desc:YES];
//        NSLog(@"车型数据 = %@",carList);
//        [carList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//            NSDictionary *jsonDic =obj;
//            if (![dbManager isTableOK:TABLE_CAR]) {
//                NSArray *fields = [jsonDic allKeys]; //字段名称
//                if (![dbManager createTable:TABLE_CAR fields:fields]) {
//                    NSLog(@"创建车系车型表失败");
//                }
//            }
//            NSArray *fieldsValue = [jsonDic allValues]; //字段对应的值
//            [dbManager insertTable:TABLE_CAR withArr:fieldsValue];
//        }];
    //    [dbManager closeDB];
}

#pragma mark 获取车系数据
-(void)loadCarBrandList{
    NSArray *arry = @[@"brandId",@"bName"];
    if (![dbManager isTableOK:TABLE_CAR]){
        return;
    }
    if(![dbManager readyDatabse]){
        [dbManager openDB];
    }
    brandList =[dbManager selectFromTable:TABLE_CAR fields:arry whereParam:nil groupBy:@[@"brandId"] orderby:nil desc:YES];
    
}
#pragma mark 获取车型数据
-(NSArray *)loadCarModelList{
    NSArray *arry = @[@"modelId",@"mName"];
    if (![dbManager isTableOK:TABLE_CAR]){
        return nil;
    }
    if(![dbManager readyDatabse]){
        [dbManager openDB];
    }
    NSString *whereParam = [NSString stringWithFormat:@"brandId = \'%@\'",brandId];
    NSArray *result = [dbManager selectFromTable:TABLE_CAR fields:arry whereParam:whereParam groupBy:nil orderby:nil desc:YES];
    return result;
}
//#pragma mark selectBTN
//
////如果有section的话  只传入section数据 如果没有section数据 只传sourcelist
//- (void)initlistView:(UIButton *)btn andSourceList:(NSArray *)sourcelist
//    andSectionSource:(NSArray *)sectionList
//    andSectionTitleArr:(NSArray *)titleList{
//    tableVC.frame = CGRectMake(btn.frame.origin.x,btn.frame.origin.y+btn.frame.size.height, btn.frame.size.width, 300);
//    tableVC.keylist = sourcelist;
//    tableVC.sectionList = sectionList;
//    tableVC.titleList = titleList;
//    [tableVC reloadData];
//    [self.scrollerView addSubview:tableVC];
//}
#pragma mark-------------------------------------------------------------
#pragma mark 选择对比车系
- (IBAction)selectBrandBtn:(id)sender {
    UIButton *btn = sender;
    btn.tag = 1000;
    tableVC.hidden = NO;
    tableVC.tag = btn.tag;
    NSMutableArray *keyList = [[NSMutableArray alloc]init];
    NSMutableArray *valueList = [[NSMutableArray alloc]init];
    [brandList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [keyList addObject:[obj objectForKey:@"bName"]];
        [valueList addObject:[obj objectForKey:@"brandId"]];

    }];
    [self initBrandlistView:btn KeyList:keyList valueList:valueList];
}
#pragma mark 获取车系数据
- (void)initBrandlistView:(UIButton *)btn KeyList:(NSArray *)keyList valueList:(NSArray *)valueList
{
    tableVC.frame =  CGRectMake(btn.frame.origin.x,btn.frame.origin.y+btn.frame.size.height, btn.frame.size.width, 300);
    tableVC.keylist = keyList;
    tableVC.valuelist = valueList;
    [tableVC reloadData];
    [self.view addSubview:tableVC];
}
#pragma mark-------------------------------------------------------------
#pragma mark 获取车型数据
- (void)initModellistView:(UIButton *)btn{
    tableVC.frame = CGRectMake(btn.frame.origin.x,btn.frame.origin.y+btn.frame.size.height, btn.frame.size.width, 300);
    NSMutableArray *keyList = [[NSMutableArray alloc]init];
    NSMutableArray *valueList = [[NSMutableArray alloc]init];
    [modelList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [keyList addObject:[obj objectForKey:@"mName"]];
        [valueList addObject:[obj objectForKey:@"modelId"]];
        
    }];
    tableVC.keylist = keyList;
    tableVC.valuelist = valueList;
    [tableVC reloadData];
    [self.scrollerView addSubview:tableVC];
}
#pragma mark 选择对比车型1
- (IBAction)selectTypeBtn1:(id)sender {
    UIButton *btn = sender;
    btn.tag = 1001;
    tableVC.hidden = NO;
    tableVC.tag = btn.tag;
    [self initModellistView:btn];
}

#pragma mark 选择对比车型2
- (IBAction)selectTypeBtn2:(id)sender {
    UIButton *btn = sender;
    btn.tag = 1002;
    tableVC.hidden = NO;
    tableVC.tag = btn.tag;
    [self initModellistView:btn];
}
#pragma mark 选择对比车型3
- (IBAction)selectOtherBtn:(id)sender {
    UIButton *btn = sender;
    tableVC.hidden = NO;
    tableVC.tag = btn.tag;
    [self initModellistView:btn];}
//增加方法
- (IBAction)selectAddBtn:(id)sender {
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(self.addBtn.frame.origin.x, 16, 324, 40)];
    button.tag = self.addBtn.tag;
   
    [button setTitleColor:[UIColor blueColor]forState:UIControlStateNormal];
    [button setTitle:@"请选择车型" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(selectOtherBtn:) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundImage:[UIImage imageNamed:@"dropdown_button@2x.png"] forState:UIControlStateNormal];
    [self.scrollerView addSubview:button];
    self.addBtn.tag ++;
    self.addBtn.frame = CGRectMake(button.frame.origin.x+button.frame.size.width +20, self.addBtn.frame.origin.y, self.addBtn.frame.size.width, self.addBtn.frame.size.height);
    self.addBtn.hidden = YES;
    self.scrollerView.contentSize = CGSizeMake( self.addBtn.frame.origin.x+ 40, self.scrollerView.frame.size.height);
    _item2TableView.frame = CGRectMake(_item2TableView.frame.origin.x, _item2TableView.frame.origin.y, self.scrollerView.contentSize.width + self.addBtn.frame.size.width, _item2TableView.frame.size.height);
    
    self.lineImgView.frame = CGRectMake(self.lineImgView.frame.origin.x, self.lineImgView.frame.origin.y, self.scrollerView.contentSize.width + self.addBtn.frame.size.width, self.lineImgView.frame.size.height);
    
    
}
#pragma mark-------------------------------------------------------------
#pragma mark GetValueDelegate
#pragma mark 获取车型对比项目list
-(NSArray *)loadTitleList:(NSString *)brandId{
    NSArray *arry = @[@"categoryName"];
    NSArray *orderarry = @[@"dOrder"];

    if (![dbManager isTableOK:TABLE_COMPLETEINFO]){
        return nil;
    }
    if(![dbManager readyDatabse]){
        [dbManager openDB];
    }
    //select categoryName from CompleteInfo WHERE bName = '奥迪A6' GROUP BY categoryName order by dOrder ASC
    NSArray *tempArr =[dbManager selectFromTable:TABLE_COMPLETEINFO fields:arry whereParam:nil groupBy:arry orderby:orderarry desc:NO];
    NSMutableArray *titleArr = [[NSMutableArray alloc]init];
    [tempArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
       [titleArr addObject:[obj objectForKey:@"categoryName"]];
    }];
    return titleArr;
}
-(NSArray *)loadTitleItemsWithCategoryName:(NSString *)categoryName{
    NSArray *arry = @[@"message"];
    NSArray *orderarry = @[@"dOrder"];
    
    if (![dbManager isTableOK:TABLE_COMPLETEINFO]){
        return nil;
    }
    if(![dbManager readyDatabse]){
        [dbManager openDB];
    }
//   Select message from CompleteInfo where bName = '奥迪A6' and categoryName = '基本性能' GROUP BY message ORDER BY dOrder ASC;
    NSString *whereParam = [NSString stringWithFormat:@"brandId = \'%@\' and categoryName = \'%@\'",brandId,categoryName];
    NSArray *tempArr =[dbManager selectFromTable:TABLE_COMPLETEINFO fields:arry whereParam:whereParam groupBy:arry orderby:orderarry desc:NO];
    NSMutableArray *itemArr = [[NSMutableArray alloc]init];
    [tempArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [itemArr addObject:[obj objectForKey:@"message"]];
    }];
    return itemArr;
}

-(NSArray *)loadItemsValue{
    // Select itemValue from CompleteInfo where bName = '奥迪A6' and categoryName = '基本性能'and modelId = '69E6ED63-DAD8-4604-957E-E53FD2FD0A82' GROUP BY itemValue ORDER BY dOrder ASC;
    NSArray *arry = @[@"itemValue"];
    NSArray *orderarry = @[@"dOrder"];
    NSArray *groupArry = @[@"message"];
    if (![dbManager isTableOK:TABLE_COMPLETEINFO]){
        return nil;
    }
    if(![dbManager readyDatabse]){
        [dbManager openDB];
    }
    NSMutableArray *values = [[NSMutableArray alloc]init];
   
    [titleList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *categoryName = obj;
        NSString *whereParam = [NSString stringWithFormat:@"brandId = \'%@\' and categoryName = \'%@\'  and modelId = \'%@\'",brandId,categoryName,modelId];
        NSArray *tempArr =[dbManager selectFromTable:TABLE_COMPLETEINFO fields:arry whereParam:whereParam groupBy:groupArry orderby:orderarry desc:NO];
         NSMutableArray *valueItem = [[NSMutableArray alloc]init];
        [tempArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
             [valueItem addObject:[obj objectForKey:@"itemValue"]];
         }];
        [values addObject:valueItem];
    }];
    
    return values;
}
- (void)updateTitleTable{
    //更新titletable
    _titleTableView.hidden = NO;
    
    titleList = [self loadTitleList:brandId];
    _titleTableView.titleList = titleList ;
    
    itemList = [[NSMutableArray alloc]init];
    [titleList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSArray *tempArr =[self loadTitleItemsWithCategoryName:obj];
        [itemList addObject:tempArr];
    }];
    _titleTableView.sectionList = itemList;
    [_titleTableView reloadData];
}
-(void)getKeyName:(NSString *)selectKey selectValue:(NSString *)selectValue tableView:(UITableView *)tableView{
    tableVC.hidden =YES;
    [tableVC removeFromSuperview];
    UIButton *button;
    //选中车系数据
    if (tableVC.tag ==1000) {
        button = (UIButton *)[self.view viewWithTag:tableView.tag];
        button.titleLabel.text = selectKey;
        brandId = selectValue;
        //更新车型数据
        modelList =[self loadCarModelList];
        
        [self updateTitleTable];
        
        return;
    }
    
    //选中车型数据
  
    button = (UIButton *)[_scrollerView viewWithTag:tableView.tag];
    button.titleLabel.text = selectKey;
    modelId = selectValue;
     _item2TableView.hidden = NO;
    if (modelList ==nil) {
        NSAssert(0,@"此车系下无车型！");
    }
    if (tableVC.tag == 1002) {
        _item2TableView.isSelectBtn2 = YES;
    }
    if (tableVC.tag == 1003) {
       _item2TableView.isSelectBtn3 = YES;
    }

     _item2TableView.titleList = nil;
     _item2TableView.sectionList = [self loadItemsValue];
    [_item2TableView reloadData];
    [self updateTitleTable];
}
#pragma mark ----------------------------------------------------------
#pragma mark ChangeCellDelegate
- (float)tableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath{
    float cellHeight = 40;
    if (tableView == _titleTableView && [_item2TableView.sectionList count]>0) {
//        NSLog(@"_item2TableView.sectionList =%@",_item2TableView.sectionList);
        UITableViewCell *cell = [_item2TableView cellForRowAtIndexPath:indexPath];
        cellHeight = cell.frame.size.height;
    }
    return cellHeight;
}
- (void)tableViewDidScroll:(UIScrollView *)scrollView{
//    NSLog(@"tableViewDidScroll contentOffset begin:%@",NSStringFromCGPoint(scrollView.contentOffset));
    if (scrollView == _titleTableView) {
        _item2TableView.contentOffset = CGPointMake(_item2TableView.contentOffset.x, _titleTableView.contentOffset.y);
    }
    
    if (scrollView == _item2TableView) {
        _titleTableView.contentOffset=  CGPointMake(_titleTableView.contentOffset.x, _item2TableView.contentOffset.y);
    }
//    NSLog(@"tableViewDidScroll contentOffset end:%@",NSStringFromCGPoint(scrollView.contentOffset));
}
#pragma mark ----------------------------------------------------------
#pragma mark 高亮 差异化
- (IBAction)hightLine:(id)sender {
    _hightLineBtn.backgroundColor = [UIColor blueColor];
    _diffInfoBtn.backgroundColor = [UIColor whiteColor];
    
    _item2TableView.isDifferent = NO;
    [_item2TableView reloadData];
    [_titleTableView reloadData];
    
}
- (IBAction)diffInfo:(id)sender {
    _diffInfoBtn.backgroundColor = [UIColor blueColor];
    _hightLineBtn.backgroundColor = [UIColor whiteColor];
    
    _item2TableView.isDifferent = YES;
    [_item2TableView reloadData];
    [_titleTableView reloadData];
}


@end
